package com.wing.product.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.utils.JsonResult;
import com.wing.product.dao.ProductAttributeCategoryDao;
import com.wing.product.model.entity.ProductAttributeCategory;
import com.wing.product.model.entity.ProductType;
import com.wing.product.model.request.ProductAttributeCategoryForm;
import com.wing.product.model.response.NodeDataVO;
import com.wing.product.model.response.ProductAttributeCategoryVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 产品属性分类-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class ProductAttributeCategoryServiceImpl extends ServiceImpl<ProductAttributeCategoryDao, ProductAttributeCategory> implements ProductAttributeCategoryService {

    private static long ROOT_ID = -1l;

    @Autowired
    private ProductTypeService productTypeService;

    @Override
    public int add(ProductAttributeCategoryForm productAttributeCategoryForm) {
        //校验
        ProductAttributeCategory productAttributeCategory = new ProductAttributeCategory();
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(ProductAttributeCategory.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(productAttributeCategoryForm, productAttributeCategory, copyOptions);
        if (productAttributeCategoryForm.getParentId() != -1) {
            ProductAttributeCategory productAttributeCategoryParent = new ProductAttributeCategory();
            productAttributeCategoryParent.setId(productAttributeCategoryForm.getParentId());
            productAttributeCategoryParent.setHasChild(true);
            if (productAttributeCategoryForm.getIsDeleted()) {
                productAttributeCategoryParent.setHasEnableChild(true);
            }
            baseMapper.updateById(productAttributeCategoryParent);
        }
        //物料类别
        ProductType productType = productTypeService.getById(productAttributeCategoryForm.getProductType());
        productAttributeCategory.setMaterialNature(productType.getMaterialNature());
        return baseMapper.insert(productAttributeCategory);
    }

    @Override
    public List<ProductAttributeCategoryVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<ProductAttributeCategoryVO> pageList4app(Page page, Map<String, Object> params) {
        List<ProductAttributeCategoryVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public ProductAttributeCategoryVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }


    @Override
    @Transactional
    public int del(Long id) {
        ProductAttributeCategoryVO productAttributeCategoryVO = baseMapper.get4appById(id);
        if (productAttributeCategoryVO != null) {
            int delCount = baseMapper.deleteById(id);
            if (productAttributeCategoryVO.getParentId() != ROOT_ID) {
                int count = baseMapper.selectCount(new QueryWrapper<ProductAttributeCategory>().eq("parent_id", productAttributeCategoryVO.getParentId()));
                if (count == 0) {
                    ProductAttributeCategory productAttributeCategoryParent = new ProductAttributeCategory();
                    productAttributeCategoryParent.setId(productAttributeCategoryVO.getParentId());
                    productAttributeCategoryParent.setHasChild(false);
                    productAttributeCategoryParent.setHasEnableChild(false);
                    baseMapper.updateById(productAttributeCategoryParent);
                }
            }

            return delCount;
        }
        return 0;
    }

    @Override
    @Transactional
    public int enable(Long id) {
        ProductAttributeCategoryVO productAttributeCategoryVO = baseMapper.get4appById(id);
        if (productAttributeCategoryVO != null) {
            ProductAttributeCategory productAttributeCategory = new ProductAttributeCategory();
            productAttributeCategory.setId(id);
            productAttributeCategory.setIsDeleted(true);
            int updateCount = baseMapper.updateById(productAttributeCategory);
            if (productAttributeCategoryVO.getParentId() != ROOT_ID) {
                ProductAttributeCategory productAttributeCategoryParent = new ProductAttributeCategory();
                productAttributeCategoryParent.setId(productAttributeCategoryVO.getParentId());
                productAttributeCategoryParent.setHasEnableChild(true);
                baseMapper.updateById(productAttributeCategoryParent);
            }

            return updateCount;
        }

        return 0;
    }

    @Override
    @Transactional
    public int disable(Long id) {
        ProductAttributeCategoryVO productAttributeCategoryVO = baseMapper.get4appById(id);
        if (productAttributeCategoryVO != null) {
            ProductAttributeCategory productAttributeCategory = new ProductAttributeCategory();
            productAttributeCategory.setId(id);
            productAttributeCategory.setIsDeleted(false);
            int updateCount = baseMapper.updateById(productAttributeCategory);
            if (productAttributeCategoryVO.getParentId() != ROOT_ID) {
                int count = baseMapper.selectCount(new QueryWrapper<ProductAttributeCategory>().eq("parent_id", productAttributeCategoryVO.getParentId()).eq("is_deleted", true));
                if (count == 0) {
                    ProductAttributeCategory productAttributeCategoryParent = new ProductAttributeCategory();
                    productAttributeCategoryParent.setId(productAttributeCategoryVO.getParentId());
                    productAttributeCategoryParent.setHasEnableChild(false);
                    baseMapper.updateById(productAttributeCategoryParent);
                }
            }

            return updateCount;
        }

        return 0;
    }

    @Override
    @Transactional
    public int update(ProductAttributeCategoryForm productAttributeCategoryForm) {
        ProductAttributeCategoryVO productAttributeCategoryVO = baseMapper.get4appById(productAttributeCategoryForm.getId());
        if (productAttributeCategoryVO != null) {
            if (!productAttributeCategoryVO.getParentId().equals(productAttributeCategoryForm.getParentId())) {
                boolean isUpdateEnable = productAttributeCategoryVO.getIsDeleted().equals(productAttributeCategoryForm.getIsDeleted());
                ProductAttributeCategory productMaterialCategory = new ProductAttributeCategory();
                BeanUtils.copyProperties(productAttributeCategoryForm, productMaterialCategory);
                baseMapper.updateById(productMaterialCategory);

                //update new parent category
                if (productAttributeCategoryForm.getParentId() != ROOT_ID) {
                    ProductAttributeCategory parentProducatAttributeCategory = new ProductAttributeCategory();
                    parentProducatAttributeCategory.setId(productAttributeCategoryForm.getParentId());
                    parentProducatAttributeCategory.setHasChild(true);
                    if (productAttributeCategoryForm.getIsDeleted()) {
                        parentProducatAttributeCategory.setHasEnableChild(true);
                    }
                    baseMapper.updateById(parentProducatAttributeCategory);
                }


                //update current db product category
                if (productAttributeCategoryVO.getParentId() != ROOT_ID) {
                    int count = baseMapper.selectCount(new QueryWrapper<ProductAttributeCategory>().eq("parent_id", productAttributeCategoryVO.getParentId()));
                    if (count == 0) {
                        ProductAttributeCategory productAttributeCategoryParent = new ProductAttributeCategory();
                        productAttributeCategoryParent.setId(productAttributeCategoryVO.getParentId());
                        productAttributeCategoryParent.setHasChild(false);
                        baseMapper.updateById(productAttributeCategoryParent);
                    }
//                if (isUpdateEnable&&!deviceCategoryForm.getIsDeleted()){
                    count = baseMapper.selectCount(new QueryWrapper<ProductAttributeCategory>().eq("parent_id", productAttributeCategoryVO.getParentId()).eq("is_deleted", true));
                    if (count == 0) {
                        ProductAttributeCategory productMaterialCategoryParent = new ProductAttributeCategory();
                        productMaterialCategoryParent.setId(productAttributeCategoryVO.getParentId());
                        productMaterialCategoryParent.setHasEnableChild(false);
                        baseMapper.updateById(productMaterialCategoryParent);
                    }
                    //                }
                }


            } else {
                boolean isUpdateEnable = productAttributeCategoryVO.getIsDeleted().equals(productAttributeCategoryForm.getIsDeleted());
                ProductAttributeCategory productAttributeCategory = new ProductAttributeCategory();
                BeanUtils.copyProperties(productAttributeCategoryForm, productAttributeCategory);
                baseMapper.updateById(productAttributeCategory);
                if (isUpdateEnable && !productAttributeCategoryForm.getIsDeleted() && productAttributeCategoryForm.getParentId() != ROOT_ID) {
                    int count = baseMapper.selectCount(new QueryWrapper<ProductAttributeCategory>().eq("parent_id", productAttributeCategoryVO.getParentId()).eq("is_deleted", true));
                    if (count == 0) {
                        ProductAttributeCategory productAttributeCategoryParent = new ProductAttributeCategory();
                        productAttributeCategoryParent.setId(productAttributeCategoryVO.getParentId());
                        productAttributeCategoryParent.setHasEnableChild(false);
                        baseMapper.updateById(productAttributeCategoryParent);
                    }
                }

            }
        }
        return 0;
    }

    @Override
    public JsonResult getTreeData(Integer materialNature, Long productType) {
        Map<String, Object> mapQuery = new HashMap<>();
        mapQuery.put("materialNature", materialNature);
        mapQuery.put("productType", productType);
        List<ProductAttributeCategoryVO> list = baseMapper.list4app(mapQuery);
        Map<Long, List<NodeDataVO>> map = new HashMap<>();
        for (ProductAttributeCategoryVO category : list) {
            if (map.containsKey(category.getParentId())) {
                NodeDataVO nodeDataVO = new NodeDataVO();
                nodeDataVO.setValue(category.getId().toString());
                nodeDataVO.setName(category.getName());
                map.get(category.getParentId()).add(nodeDataVO);
            } else {
                List<NodeDataVO> tmpList = new ArrayList<>();
                NodeDataVO nodeDataVO = new NodeDataVO();
                nodeDataVO.setValue(category.getId().toString());
                nodeDataVO.setName(category.getName());
                tmpList.add(nodeDataVO);
                map.put(category.getParentId(), tmpList);
            }
        }
        List<NodeDataVO> rootList = map.get(-1L);
        if (rootList == null) {
            return JsonResult.success();
        }
        constructTree(rootList, map);
        return JsonResult.success(rootList);
    }

    private void constructTree(List<NodeDataVO> parentList, Map<Long, List<NodeDataVO>> dataMap) {
        for (NodeDataVO node : parentList) {
            Long nodeId = Long.valueOf(node.getValue());
            List<NodeDataVO> childList = dataMap.get(nodeId);
            if (childList != null) {
                node.setChildren(childList);
                constructTree(childList, dataMap);
            }
        }
    }
}
